思路:通过当前值target与集合中的每项做减法,得到的差值去集合中查找,如果集合中存在,直接返回角标数据,然后不存在,就把数据添加到集合中,依次比较。
public int[] twoSum(int[] nums, int target) {
if(nums==null || nums.length==0)
return null;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (map.containsKey(diff)) {
return new int[]{map.get(diff), i};
}
map.put(nums[i], i);
}
return null;
}